package com.blb.goods_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blb.goods_service.entity.Brand;
import com.blb.goods_service.entity.Category;
import com.blb.goods_service.entity.CategoryBO;
import com.blb.goods_service.entity.CategoryBrand;
import com.blb.goods_service.mapper.CategoryBrandMapper;
import com.blb.goods_service.mapper.CategoryMapper;
import com.blb.goods_service.service.ICategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    private Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Transactional
    @Override
    public Category saveCategory(CategoryBO category) {
        Category cate = new Category();
        //1）通过当前父节点的子节点数量，计算出sort的值
        Integer count = categoryMapper.selectCount(new QueryWrapper<Category>().lambda()
                .eq(Category::getParentId, category.getParentId()));
        cate.setSort(count + 1);
        //2）修改父分类的isParent字段为1
        Category parent = categoryMapper.selectOne(new QueryWrapper<Category>().lambda()
                .eq(Category::getId, category.getParentId()));
        parent.setIsParent(1);
        categoryMapper.updateById(parent);
        //3）添加分类信息
        cate.setName(category.getName());
        cate.setParentId(category.getParentId());
        cate.setIsParent(0);
        categoryMapper.insert(cate);
        //5）添加后获得新分类的id
        logger.debug("分类id：" +cate.getId());
        //6）向分类品牌表添加数据
        //7）判断当前分类和品牌是否存在，如果不存在再添加
        for(Brand brand : category.getSelectedBrands()){
            Integer count2 = categoryBrandMapper.selectCount(new QueryWrapper<CategoryBrand>()
                    .lambda().eq(CategoryBrand::getBrandId, brand.getId())
                    .eq(CategoryBrand::getCategoryId, cate.getId()));
            if(count2 == 0){
                categoryBrandMapper.insert(new CategoryBrand(cate.getId(),brand.getId()));
            }
        }
        logger.debug("完成添加：" +cate);
        return cate;
    }
}
